package com.flyiu.data.consistency.service;

import java.util.List;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.flyiu.data.consistency.check.CheckBack;
import com.flyiu.data.consistency.context.DistributedTransactionContext;
import com.flyiu.data.consistency.model.DistributedTransactionInstance;
import com.flyiu.data.consistency.model.DistributedTransactionPartner;
import com.flyiu.data.consistency.model.DistributedTransactionState;
import com.flyiu.data.consistency.repository.DistributedTransactionInstanceRepository;
@Component
public class RecoverServiceImpl implements RecoverService {
	
	private static Logger LOG = LoggerFactory.getLogger(RecoverServiceImpl.class);
	
	@Autowired
	private DistributedTransactionInstanceRepository instanceRepository;
	@Autowired
	private DistributeService service;
	
	@Autowired
	private CheckBack checkBack;
	
	/* (non-Javadoc)
	 * @see com.flyiu.data.consistency.service.RecoverService#recoverOne(com.flyiu.data.consistency.model.DistributedTransactionInstance)
	 */
	@Override
//	@Transactional(transactionManager="consistencyTransactionManager",propagation=Propagation.REQUIRES_NEW)
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void recoverOne(DistributedTransactionInstance distributedTransactionInstance) {
		
		DistributedTransactionInstance instance = instanceRepository.lockInstance(distributedTransactionInstance.getTransactionState(), distributedTransactionInstance.getId());
		 List<DistributedTransactionPartner> partners =  instance.getPartners();
		
		boolean isCommit = checkBack.isCommit(distributedTransactionInstance.getBusinessId());
		
		LOG.info(isCommit+"");
		DistributedTransactionContext.setInstance(instance);
		if(distributedTransactionInstance.getTransactionState() == DistributedTransactionState.PRE_COMMIT){
			service.commit();
		}
		
		if(distributedTransactionInstance.getTransactionState() == DistributedTransactionState.PRE_CANCEL){
			service.rollback();
		}
	}
	
	
	/* (non-Javadoc)
	 * @see com.flyiu.data.consistency.service.RecoverService#recover(com.flyiu.data.consistency.model.DistributedTransactionInstance)
	 */
	@Override
	@Async
	public void recover(DistributedTransactionInstance distributedTransactionInstance) {
		recoverOne(distributedTransactionInstance);
	}
}
